<template>
  <div class="container">
    <Tabs type="card">
      <TabPane label="Login">
        <h1>Login</h1>
        <br />
        <Form class="form" ref="loginParams" :model="loginParams" :rules="ruleValidate" :label-width="80">
          <FormItem label="E-mail" prop="email">
            <Input v-model="loginParams.email" placeholder="Please enter your e-mail" clearable></Input>
          </FormItem>
          <FormItem label="Password" prop="password">
            <Input v-model="loginParams.password" placeholder="Please enter your password" type="password" clearable></Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSubmit('loginParams')">Login</Button>
            <Button @click="handleReturn" style="margin-left: 8px">Return</Button>
          </FormItem>
        </Form>
      </TabPane>
      <TabPane label="Register">
        <h1>Register</h1>
        <br />
        <Form class="form" ref="registerParams" :model="registerParams" :rules="ruleValidate" :label-width="80">
          <FormItem label="Name" prop="username">
            <Input v-model="registerParams.username" placeholder="Please enter your name" clearable></Input>
          </FormItem>
          <FormItem label="E-mail" prop="email">
            <Input v-model="registerParams.email" placeholder="Please enter your e-mail" clearable></Input>
          </FormItem>
          <FormItem label="Password" prop="password">
            <Input v-model="registerParams.password" placeholder="Please enter your password" type="password" clearable></Input>
          </FormItem>
          <FormItem label="Confirm" prop="passwordCheck">
            <Input v-model="registerParams.passwordCheck" placeholder="Please enter your password again" type="password" clearable></Input>
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleSubmit('registerParams')">Register</Button>
            <Button @click="handleReturn" style="margin-left: 8px">Return</Button>
          </FormItem>
        </Form>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
import userApi from '@/api/user'
import { mapActions } from 'vuex'

export default {
  name: 'Login',
  data() {
    // 校验密码
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please enter your password'))
      } else {
        if (this.registerParams.passwordCheck !== '') {
          // 对第二个密码框单独验证
          this.$refs.registerParams.validateField('passwordCheck')
        }
        callback()
      }
    }
    const validatePassCheck = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('Please enter your password again'))
      } else if (value !== this.registerParams.password) {
        callback(new Error('The two input passwords do not match!'))
      } else {
        callback()
      }
    }
    return {
      loginParams: {
        email: '',
        password: ''
      },
      registerParams: {
        username: '',
        email: '',
        password: '',
        passwordCheck: ''
      },
      ruleValidate: {
        username: [{ required: true, message: 'The username cannot be empty', trigger: 'blur' }],
        email: [
          { required: true, message: 'Mailbox cannot be empty', trigger: 'blur' },
          { type: 'email', message: 'Incorrect email format', trigger: 'blur' }
        ],
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        passwordCheck: [{ required: true, validator: validatePassCheck, trigger: 'blur' }]
      }
    }
  },
  methods: {
    ...mapActions(['handleLogin', 'getUserInfo']),
    handleSubmit(name) {
      const that = this
      this.$refs[name].validate(async valid => {
        if (valid) {
          try {
            // 注册
            if (name !== 'loginParams') {
              let { passwordCheck, ...params } = this.registerParams
              let res = await userApi.register(params)
              // console.log(res)
              let { code } = res
              if (code === 'request_ok') {
                this.$Message.success(res.message)
              } else {
                this.$Message.info(res.message)
              }
            } else {
              // 登陆
              let params = Object.assign({}, this.loginParams)
              await this.handleLogin(params)
              await this.getUserInfo()
              let redirect = decodeURIComponent(this.$route.query.redirect || '/')
              this.$router.push({
                path: redirect
              })
            }
          } catch (error) {
            console.error(error)
          }
        }
      })
    },
    handleReturn() {
      this.$router.push({
        name: 'index'
      })
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  width: 400px;
  height: 400px;
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
}
</style>
